package com.lzw.DailyAudit.service.dateAggregation_02;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.hooya.fa.eu.biz.DailyAudit.entity.DailyAuditStatus;
import com.hooya.fa.eu.biz.DailyAudit.entity.StkOrigDataCollect;
import com.hooya.fa.eu.biz.DailyAudit.entity.dto.CGDataDTO;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyAuditStatusMapper;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyMetaStkCustomsMapper;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyTempJcjlMapper;
import com.hooya.integrated.common.util.times.DateExtUtil;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@DS("fa_eu_daily")
public class Insert_CG {

	@Autowired
	private DailyTempJcjlMapper tempJcjlMapper;

	@Autowired
	private DailyMetaStkCustomsMapper metaStkCustomsMapper;

	@Autowired
	private CommonService commonService;

	@Autowired
	private DailyAuditStatusMapper statusMapper;

	final List<String> toEmails = Collections.singletonList("apple.lan@fdsintl.com");

	public void insert_cg(String currentDate) {
		try {

			String name = "insertCg-02";
			DailyAuditStatus dailyAuditStatus = statusMapper.selectStatus(name, currentDate);
			if (dailyAuditStatus != null && dailyAuditStatus.getFlag() == 1) {
				log.info("{} - 该方法已执行，进行跳过！", name);
				return;
			}

			log.info("开始执行采购数据插入任务，开始日期：{}", currentDate);

			// 获取主要数据
			List<CGDataDTO> mainData = tempJcjlMapper.getCgData(currentDate);

			//重新设置belongs值 和 hthm的值
			mainData.forEach(f -> {
				if (f.getBelongs() != null && f.getBelongs().toLowerCase().startsWith("fds")) {
					String[] parts = f.getBelongs().split("-");
					f.setBelongs(parts[0]);
				}
				if (f.getHthm() != null && f.getHthm().contains("-")) {
					String[] parts = f.getHthm().split("-");
					if (parts.length > 0) {
						String lastPart = parts[parts.length - 1];
						if (lastPart.matches("\\d+")) {  // 检查是否为纯数字
							StringBuilder result = new StringBuilder();
							for (int i = 0; i < parts.length - 1; i++) {
								if (i > 0) result.append("-");
								result.append(parts[i]);
							}
							f.setHthm(result.toString());
						}
					}
				}
			});

			// 获取价格数据（只包含有价格的记录）
			List<CGDataDTO> priceData = metaStkCustomsMapper.getCgPriceData();

			// 合并主数据和价格数据
			Map<String, List<CGDataDTO>> PriceDataMap = priceData.stream().collect(Collectors.groupingBy(f -> f.getSku() + "|" + f.getInvoiceno()));
			List<CGDataDTO> mergeData = new ArrayList<>();
			for (CGDataDTO mainItem : mainData) {
				String key = mainItem.getCpbh() + "|" + mainItem.getHthm();
				if (PriceDataMap.containsKey(key)) {
					List<CGDataDTO> cgDataDTOS = PriceDataMap.get(key);
					cgDataDTOS.forEach(f -> {
						CGDataDTO newItem = new CGDataDTO();
						BeanUtils.copyProperties(mainItem, newItem);
						newItem.setInvoicedate(f.getInvoicedate());
						newItem.setPrice(f.getPrice());
						newItem.setCurrency(f.getCurrency());
						newItem.setQty(f.getQty());
						newItem.setSku(f.getSku());
						newItem.setInvoiceno(f.getInvoiceno());
						mergeData.add(newItem);
					});
				} else {
					mergeData.add(mainItem);
				}
			}

			// 按qty排序并分组，获取第一条记录
			Map<String, List<CGDataDTO>> groupedData = mergeData.stream().sorted(Comparator.comparing(CGDataDTO::getQty, Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.groupingBy(f -> f.getCpbh() + f.getHthm() + f.getSl()));

			// 取每组第一条记录
			Map<String, CGDataDTO> withPriceDataMap = new HashMap<>();
			for (String key : groupedData.keySet()) {
				List<CGDataDTO> group = groupedData.get(key);
				if (!withPriceDataMap.containsKey(key) && !group.isEmpty()) {
					withPriceDataMap.put(key, group.get(0));
				}
			}
			//  获得price为空的数据
			List<CGDataDTO> lastData = new ArrayList<>(withPriceDataMap.values());

			List<CGDataDTO> noPriceData = lastData.stream().filter(f -> f.getPrice() == null).collect(Collectors.toList());
			List<String> missingPriceSkuList = new ArrayList<>();
			if (!noPriceData.isEmpty()) {
				List<String> skuList = noPriceData.stream()
						.map(CGDataDTO::getCpbh)  // 获取 cpbh
						.collect(Collectors.toList());
				//从清关表中取对应cpbh的数据 - 这里取得是所有的list的数据
				String date = DateExtUtil.getBeforeNMonth(6, currentDate);
				List<CGDataDTO> giftAllPrice = metaStkCustomsMapper.getDataBySkuList(skuList, date);
				if (giftAllPrice.isEmpty()) log.error("有异常数据：{}", skuList);

				//修改lastData数据 查找异常的Sku记录到missingPriceSkuList
				noPriceData.forEach(row -> {
					String cpbh = row.getCpbh();
					String belongs = row.getBelongs();
					String sheetNumber = row.getSheetnumber();

					// 尝试不同的匹配策略
					List<CGDataDTO> matchedData = findMatchedData(giftAllPrice,cpbh, belongs);

					if (!matchedData.isEmpty()) {
						addPrice(matchedData, lastData, sheetNumber);
					} else {
						handleNoMatchScenario(cpbh, sheetNumber, lastData, missingPriceSkuList);
					}
				});
			}

			//人工介入 - 没有清关价格的cpbh
			if (!missingPriceSkuList.isEmpty()) {
				log.error("无价格的产品编号数据：{}", missingPriceSkuList);
				commonService.sendTextEmail("没有价格数据的产品编号", "当天时间为：" + currentDate + " 以下的产品编号没有数据: " + missingPriceSkuList + "劳烦解决！", toEmails);
			}

			// 数据验证
			commonService.dataVerificationCg(lastData);

			// 转换为StkOrigdataCollect对象并插入
			List<StkOrigDataCollect> records = commonService.convertGgToStkOrigDataCollect(lastData);

			commonService.batchInsert(records);

			// 修改执行状态
			commonService.UpdateOrInsertStatus(dailyAuditStatus, name, currentDate);

			log.info("insertCG执行成功");
			XxlJobHelper.log("insertCG执行成功");
		} catch (Exception e) {
			log.error("采购数据插入任务失败", e);
			XxlJobHelper.log("采购数据插入任务失败");
			throw new RuntimeException("采购数据插入任务失败", e);
		}
	}

	private static void addPrice(List<CGDataDTO> changeData, List<CGDataDTO> lastData, String sheetNumber) {
		// 按 invoiceDate 降序排序并取第一条
		CGDataDTO Price = changeData.stream().min((a, b) -> b.getInvoicedate().compareTo(a.getInvoicedate())).get();
		// 更新 lastData 中对应记录的价格信息
		lastData.stream()
				.filter(item -> item.getSheetnumber().equals(sheetNumber))
				.forEach(item -> {
					item.setPrice(Price.getPrice());
					item.setInvoicedate(Price.getInvoicedate());
					item.setCurrency(Price.getCurrency());
				});
	}

	/**
	 * 查找匹配的数据，按优先级尝试不同策略
	 */
	private List<CGDataDTO> findMatchedData(List<CGDataDTO> giftAllPrice,String cpbh, String belongs) {
		// 策略1: 相同公司 + 相同清关地
		List<CGDataDTO> result = giftAllPrice.stream()
				.filter(item -> cpbh.equals(item.getSku()) && belongs.equalsIgnoreCase(item.getBelongs()))
				.collect(Collectors.toList());

		if (!result.isEmpty()) {
			return result;
		}

		// 策略2: 不同公司 + 相同清关地
		String alternativeBelongs = getAlternativeBelongs(belongs);
		if (!alternativeBelongs.isEmpty()) {
			result = giftAllPrice.stream()
					.filter(item -> cpbh.equals(item.getSku()) && alternativeBelongs.equalsIgnoreCase(item.getBelongs()))
					.collect(Collectors.toList());
			if (!result.isEmpty()) {
				return result;
			}
		}

		// 策略3: 相同公司 + 不同清关地
		String sameCompany = getSameCompany(belongs);
		if (!sameCompany.isEmpty()) {
			result = giftAllPrice.stream()
					.filter(item -> cpbh.equals(item.getSku()) && item.getBelongs() != null && item.getBelongs().toUpperCase().startsWith(sameCompany.toUpperCase()))
					.collect(Collectors.toList());
			if (!result.isEmpty()) {
				return result;
			}
		}

		// 策略4: 不同公司 + 不同清关地
		String differentCompany = getDifferentCompany(belongs);
		if (!differentCompany.isEmpty()) {
			result = giftAllPrice.stream()
					.filter(item -> cpbh.equals(item.getSku()) && item.getBelongs() != null && item.getBelongs().toUpperCase().startsWith(differentCompany.toUpperCase()))
					.collect(Collectors.toList());
		}

		return result;
	}

	/**
	 * 处理无匹配数据的情况
	 */
	private void handleNoMatchScenario(String cpbh, String sheetNumber, List<CGDataDTO> lastData,List<String> missingPriceSkuList) {
		// 设置默认值
		lastData.stream()
				.filter(item -> item.getSheetnumber().equals(sheetNumber))
				.forEach(item -> {
					item.setPrice(0.0);
					item.setInvoicedate(null);
					item.setCurrency("");
				});
		missingPriceSkuList.add(cpbh);
	}

	/**
	 * 获取替代的belongs（不同公司+相同清关地）
	 */
	private String getAlternativeBelongs(String belongs) {
		String[] parts = belongs.split("-");
		if (parts.length < 2) return "";

		String company = parts[0];
		String country = parts[1];

		switch (company) {
			case "costway": return "fds-" + country;
			case "fds": return "costway-" + country;
			default: return "";
		}
	}

	/**
	 * 获取相同公司（用于策略3）
	 */
	private String getSameCompany(String belongs) {
		String[] parts = belongs.split("-");
		if (parts.length < 1) return "";

		String company = parts[0];
		return "costway".equals(company) || "fds".equals(company) ? company : "";
	}

	/**
	 * 获取不同公司（用于策略4）
	 */
	private String getDifferentCompany(String belongs) {
		String[] parts = belongs.split("-");
		if (parts.length < 1) return "";

		String company = parts[0];
		switch (company) {
			case "costway": return "fds";
			case "fds": return "costway";
			default: return "";
		}
	}


}